<template>
  <div style="width: 100%">
    <div class="flex-center bgc-white p12 mb16">
      <SelectCompanyGroup />
      <a-month-picker v-model="date" placeholder="选择月份" class="ml16" style="width: 160px" @change="onDateChange" />
    </div>
    <div class="flex-center bgc-white p12 mb16">
      <SelectWithInputAdd
        v-model="socAccount"
        editable
        allowClear
        mode="select"
        dictCode="1220"
        placeholder="社保账号"
        style="width: 160px"
        @change="onSearchChange"
      />
      <SelectWithInputAdd
        v-model="meAccount"
        editable
        allowClear
        mode="select"
        dictCode="1221"
        placeholder="医保账号"
        class="ml16"
        style="width: 160px"
        @change="onSearchChange"
      />
      <SelectWithInputAdd
        v-model="pfAccount"
        editable
        allowClear
        mode="select"
        dictCode="1222"
        placeholder="公积金账号"
        class="ml16"
        style="width: 160px"
        @change="onSearchChange"
      />
      <AreaPicker :level="2" allowClear placeholder="参保城市" class="ml16" style="width: 160px" @change="handleCity($event)" />
      <SelectWithInputAdd
        v-model="contractSubject"
        editable
        allowClear
        mode="select"
        dictCode="1223"
        placeholder="签约主体"
        class="ml16"
        style="width: 160px"
        @change="onSearchChange"
      />
    </div>
    <div v-if="amounts" class="flex">
      <div class="bgc-white p12 mb16 flex-center mr16 br4" style="flex: 1">
        <div class="pl12 pr24" style="border-right: 1px solid #e8e8e8; width: 240px; flex-shrink: 0">
          <div class="flex-center">
            <img src="./ic1.png" class="mr12" style="width: 40px; height: 40px" />
            <div>
              <div class="fs12" style="color: rgba(166, 168, 180, 1)">社保公积金总金额</div>
              <div class="fs16 fw500 mv4">{{ amounts.allAmount }}</div>
              <div class="fs12 flex-center" style="color: rgba(166, 168, 180, 1)">
                较上月
                <img
                  v-if="amounts.lastAllAmount && amounts.lastAllAmount > 0"
                  src="./zs2.png"
                  class="mh4"
                  style="width: 16px; height: 16px"
                />
                <img
                  v-else-if="amounts.lastAllAmount && amounts.lastAllAmount < 0"
                  src="./zs1.png"
                  class="mh4"
                  style="width: 16px; height: 16px"
                />
                <span v-if="amounts.lastAllAmount && amounts.lastAllAmount > 0" style="color: rgba(228, 31, 31, 1)">{{
                  Math.abs(amounts.lastAllAmount)
                }}</span>
                <span v-else-if="amounts.lastAllAmount && amounts.lastAllAmount < 0" style="color: rgba(109, 212, 0, 1)">{{
                  Math.abs(amounts.lastAllAmount)
                }}</span>
                <span v-else>{{ amounts.lastAllAmount }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="ph12 ml24" style="flex: 1">
          <div class="flex-center">
            <img src="./ic2.png" class="mr12" style="width: 40px; height: 40px" />
            <div>
              <div class="fs12" style="color: rgba(166, 168, 180, 1)">社保合计（元）</div>
              <div class="fs16 fw500 mv4">{{ amounts.socAmount }}</div>
              <div class="fs12 flex-center" style="color: rgba(166, 168, 180, 1)">
                较上月
                <img
                  v-if="amounts.lastSocAmount && amounts.lastSocAmount > 0"
                  src="./zs2.png"
                  class="mh4"
                  style="width: 16px; height: 16px"
                />
                <img
                  v-else-if="amounts.lastSocAmount && amounts.lastSocAmount < 0"
                  src="./zs1.png"
                  class="mh4"
                  style="width: 16px; height: 16px"
                />
                <span v-if="amounts.lastSocAmount && amounts.lastSocAmount > 0" style="color: rgba(228, 31, 31, 1)">{{
                  Math.abs(amounts.lastSocAmount)
                }}</span>
                <span v-else-if="amounts.lastSocAmount && amounts.lastSocAmount < 0" style="color: rgba(109, 212, 0, 1)">{{
                  Math.abs(amounts.lastSocAmount)
                }}</span>
                <span v-else>{{ amounts.lastSocAmount }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="ph12 ml24" style="flex: 1">
          <div class="flex-center">
            <img src="./ic3.png" class="mr12" style="width: 40px; height: 40px" />
            <div>
              <div class="fs12" style="color: rgba(166, 168, 180, 1)">公积金合计（元）</div>
              <div class="fs16 fw500 mv4">{{ amounts.pfAmount }}</div>
              <div class="fs12 flex-center" style="color: rgba(166, 168, 180, 1)">
                较上月
                <img
                  v-if="amounts.lastPfAmount && amounts.lastPfAmount > 0"
                  src="./zs2.png"
                  class="mh4"
                  style="width: 16px; height: 16px"
                />
                <img
                  v-else-if="amounts.lastPfAmount && amounts.lastPfAmount < 0"
                  src="./zs1.png"
                  class="mh4"
                  style="width: 16px; height: 16px"
                />
                <span v-if="amounts.lastPfAmount && amounts.lastPfAmount > 0" style="color: rgba(228, 31, 31, 1)">{{
                  Math.abs(amounts.lastPfAmount)
                }}</span>
                <span v-else-if="amounts.lastPfAmount && amounts.lastPfAmount < 0" style="color: rgba(109, 212, 0, 1)">{{
                  Math.abs(amounts.lastPfAmount)
                }}</span>
                <span v-else>{{ amounts.lastPfAmount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="bgc-white p12 mb16 flex-center br4" style="width: 25%; flex-shrink: 0">
        <div class="ph12">
          <div class="flex-center">
            <img src="./ic4.png" class="mr12" style="width: 40px; height: 40px" />
            <div>
              <div class="fs12" style="color: rgba(166, 168, 180, 1)">总在保人员</div>
              <div class="fs16 fw500 mv4">{{ amounts.empCount }}</div>
              <div class="fs12 flex-center" style="color: rgba(166, 168, 180, 1)">
                较上月
                <img
                  v-if="amounts.lastEmpCount && amounts.lastEmpCount > 0"
                  src="./zs2.png"
                  class="mh4"
                  style="width: 16px; height: 16px"
                />
                <img
                  v-else-if="amounts.lastEmpCount && amounts.lastEmpCount < 0"
                  src="./zs1.png"
                  class="mh4"
                  style="width: 16px; height: 16px"
                />
                <span v-if="amounts.lastEmpCount && amounts.lastEmpCount > 0" style="color: rgba(228, 31, 31, 1)">{{
                  Math.abs(amounts.lastEmpCount)
                }}</span>
                <span v-else-if="amounts.lastEmpCount && amounts.lastEmpCount < 0" style="color: rgba(109, 212, 0, 1)">{{
                  Math.abs(amounts.lastEmpCount)
                }}</span>
                <span v-else>{{ amounts.lastEmpCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="itemStatsList && itemStatsList.length > 0" class="bgc-white p12 mb16 flex-center" style="width: 100%; overflow: auto">
      <div v-for="item in itemStatsList" :key="item.name" class="pv12 ph16 ta-center" style="width: 16.66%">
        <div class="fs16 fw500" style="white-space: nowrap">{{ item.itemName }}</div>
        <div class="flex-center-center fs18 fw500 mt4">
          <img src="./m.png" class="mr4" style="width: 21px; height: 20px; margin-left: -20px" />
          {{ item.amount }}
        </div>
      </div>
    </div>
    <div class="bgc-white p12" style="width: calc(100vw - 180px - 60px)">
      <div class="flex-center-between mb16">
        <a-input-search v-model="nameOrIdCard" placeholder="搜索姓名/身份证号" style="width: 300px" @change="onSearchChange" />
        <a-space :size="16">
          <a-popover v-model="popVisible" trigger="click">
            <span class="pointer">选择表头 <a-icon type="menu" /></span>
            <div slot="content" class="bgc-white" style="width: 800px">
              <div class="p12" style="height: 400px; overflow: auto">
                <div v-for="(item, idx) in columnsFullTemp" :key="item.dataIndex">
                  <div class="fs16 fw500" :class="{ mt16: idx !== 0 }">
                    {{ item.title }}
                    <a-checkbox :checked="item.selectAll" @change="onSelectAll($event, idx)" />
                  </div>
                  <Draggable v-model="item.children" class="flex-center" style="flex-wrap: wrap">
                    <div
                      v-for="(subItem, subIdx) in item.children"
                      :key="subItem.dataIndex"
                      class="item"
                      :class="{
                        disabled: subItem.disabled,
                        selected: !subItem.disabled && subItem.selected
                      }"
                      @click="onSelectedToggle(subIdx, idx)"
                    >
                      {{ subItem.title }}
                    </div>
                  </Draggable>
                </div>
              </div>
              <div class="p16 flex-center-end">
                <a-button size="small" class="mr16" @click="onColumnCancel">取消</a-button>
                <a-button size="small" type="primary" @click="onColumnConfirm">确定</a-button>
              </div>
            </div>
          </a-popover>
          <a-button type="primary" @click="doExport">全部导出</a-button>
        </a-space>
      </div>
      <a-table
        :columns="columnsSelected"
        :dataSource="dataSource"
        :pagination="pagination"
        :scroll="{ x: 1000 }"
        size="middle"
        rowKey="id"
        @change="onTableChange"
      >
        <a slot="columnsAction" slot-scope="text, record" @click="goDetail(record)">详情</a>
      </a-table>
    </div>
  </div>
</template>
<script>
import { buildColumns, selectedToggleColumns, updateColumns, selectAllColumns, decodeColumns } from "./funcs";
import Draggable from "vuedraggable";
import SelectCompanyGroup from "@/components/SelectCompany";
import { mapState } from "vuex";
import Moment from "moment";
import SelectWithInputAdd from "xqjr-plugin-form/components/XqSelectWithInputAdd.vue";
import { AreaPicker } from "xqjr-plugin-common";
import { getToken } from "xqjr-module-auth/utils";
import axios from "axios";
export default {
  name: "",
  components: { Draggable, SelectCompanyGroup, SelectWithInputAdd, AreaPicker },
  mixins: [],
  props: {},
  data() {
    return {
      nameOrIdCard: "",
      socAccount: "",
      meAccount: "",
      pfAccount: "",
      city: "",
      contractSubject: "",
      date: Moment(),
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      amounts: null,
      itemStatsList: [],
      dataSource: [],
      columnsFullTemp: [],
      columnsFull: [],
      columnsSelected: [],
      popVisible: false
    };
  },
  computed: {
    ...mapState(["site"]),
    subjectType() {
      return this.site.selectType;
    },
    subjectId() {
      return this.site.selectId;
    }
  },
  watch: {
    subjectId: {
      handler(newVal) {
        if (newVal) {
          this.loadHead();
          this.loadData();
        }
      },
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    goDetail(record) {
      this.$store.commit("hr/updateCompany", {
        id: record.companyId,
        name: record.companyName
      });
      this.$router.push({
        path: `/shebao/shebaoMingDan/detailed/${record.empId}`,
        query: {
          id: record.id,
          year: record.year,
          month: record.month,
          prevpage: "/overview/shebao",
          disable: record.empExist === null ? false : record.empExist === 1
        }
      });
    },
    onSearchChange() {
      this.pagination.current = 1;
      this.loadData();
    },
    handleCity(e) {
      if (e.value.length > 0) {
        const value = e.value;
        const label = e.label;
        this.city = value[value.length - 1];
      } else {
        this.city = "";
      }
      this.pagination.current = 1;
      this.loadData();
    },
    doExport() {
      const data = this.buildParams();
      axios({
        url: `/hr/api/v1/socPlanDispatchUsers/exportSocOverviewList`,
        method: "post",
        data: {
          ...data,
          exportHead: decodeColumns(this.columnsFull)
        },
        responseType: "blob",
        headers: {
          token: getToken(),
          "Content-Type": "application/json"
        }
      })
        .then((res) => {
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const blob = new Blob([res.data], { type: "application/octet-stream" });
            const link = document.createElement("a");
            link.download = `${this.date.format("YYYY-MM")}-社保概览.xlsx`;
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
        .catch((err) => {
          console.log("exportSocOverviewList", err);
        });
    },
    onDateChange() {
      this.loadData();
    },
    onTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadData(false);
    },
    buildParams() {
      const data = {
        pageSize: this.pagination.pageSize,
        pageNo: this.pagination.current,
        date: this.date.format("YYYY-MM"),
        type: {
          type: this.subjectType,
          id: this.subjectId
        }
      };
      if (this.nameOrIdCard) {
        data["nameOrIdCard"] = this.nameOrIdCard;
      }
      if (this.socAccount) {
        data["socAccount"] = this.socAccount;
      }
      if (this.meAccount) {
        data["meAccount"] = this.meAccount;
      }
      if (this.pfAccount) {
        data["pfAccount"] = this.pfAccount;
      }
      if (this.city) {
        data["city"] = this.city;
      }
      if (this.contractSubject) {
        data["contractSubject"] = this.contractSubject;
      }
      return data;
    },
    loadData(doUpdate = true) {
      const data = this.buildParams();
      this.$request({
        url: `/hr/api/v1/socPlanDispatchUsers/socOverviewListStats`,
        method: "post",
        data
      })
        .then((res) => {
          this.dataSource = res.data.entities;
          this.pagination.total = res.data.entityCount;
        })
        .catch((err) => {
          console.log("socOverviewListStats", err);
        });
      if (doUpdate) {
        this.$request({
          url: `/hr/api/v1/socPlanDispatchUsers/socOverviewItemStats`,
          method: "post",
          data
        })
          .then((res) => {
            this.itemStatsList = res.data.itemStatsList;
          })
          .catch((err) => {
            console.log("socOverviewItemStats", err);
          });
        this.$request({
          url: `/hr/api/v1/socPlanDispatchUsers/socOverviewAmountStats`,
          method: "post",
          data
        })
          .then((res) => {
            this.amounts = res.data;
          })
          .catch((err) => {
            console.log("socOverviewAmountStats", err);
          });
      }
    },
    // 表头处理
    async loadHead() {
      await this.$request({
        url: `/hr/api/v1/socPlanDispatchUsers/socOverviewListHead`
      })
        .then((res) => {
          const { columnsFull, columnsSelected } = buildColumns(res.data);
          this.columnsFullTemp = columnsFull;
          this.columnsFull = columnsFull;
          this.columnsSelected = columnsSelected;
        })
        .catch((err) => {
          console.log("socOverviewListHead", err);
        });
    },
    onColumnCancel() {
      this.popVisible = false;
      this.columnsFullTemp = JSON.parse(JSON.stringify(this.columnsFullTemp));
    },
    onColumnConfirm() {
      this.popVisible = false;
      this.$request({
        url: `/hr/api/v1/socPlanDispatchUsers/saveSocOverviewListUserHead`,
        method: "post",
        data: decodeColumns(this.columnsFullTemp)
      })
        .then((res) => {
          this.loadHead();
        })
        .catch((err) => {
          console.log("saveSocOverviewListUserHead", err);
        });
    },
    onSelectAll(evt, idx) {
      this.columnsFullTemp = selectAllColumns(idx, this.columnsFullTemp, evt.target.checked);
    },
    onSelectedToggle(subIdx, idx) {
      this.columnsFullTemp = selectedToggleColumns(subIdx, idx, this.columnsFullTemp);
    }
  }
};
</script>
<style lang="scss" scoped>
.item {
  font-size: 12px;
  line-height: 24px;
  padding: 0 12px;
  background: rgba(243, 247, 251, 1);
  border-radius: 4px;
  margin-right: 12px;
  margin-top: 12px;
  cursor: pointer;
  border: 1px solid #fff;
  &.disabled {
    background: rgba(229, 229, 229, 1);
    cursor: not-allowed;
  }
  &.selected {
    position: relative;
    background: #fff;
    color: var(--primary);
    border: 1px solid var(--primary);
    &:before {
      content: "";
      position: absolute;
      z-index: 1;
      right: 0;
      bottom: 0;
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 0 0 16px 16px;
      border-color: transparent transparent var(--primary) transparent;
    }
    &:after {
      position: absolute;
      right: 1px;
      bottom: 4px;
      content: "";
      color: #fff;
      width: 7px;
      height: 3px;
      display: inline-block;
      border: 1px solid #fff;
      border-width: 0 0 1px 2px;
      transform: rotate(-45deg);
      vertical-align: baseline;
      z-index: 1;
    }
  }
}
</style>
